//
//  ConfirmPayVC.swift
//  RPay
//
//  Created by CharlieLiao on 2017/7/8.
//  Copyright © 2017年 Charlie. All rights reserved.
//

import LocalAuthentication

class ConfirmPayVC: BaseVC, CTAPIManagerParamSource, CTAPIManagerCallBackDelegate {
    
    // MARK: - Init
    convenience init() {
        self.init(nibName: "ConfirmPayView", bundle: nil)
        modalPresentationStyle = .overCurrentContext
        modalTransitionStyle = .crossDissolve
    }
    
    // MARK: - Life Cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        alertView.layer.cornerRadius = 4
        alertView.layer.masksToBounds = true
        // Do any additional setup after loading the view.
        amountLabel.text = money
        pwdTF.inputAccessoryView = UIView()
        
        /// 手机是否支持指纹支付
        let content = LAContext()
        var err: NSError?
        if !content.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &err) {
            if #available(iOS 9.0, *) {
                if err!.code == LAError.touchIDLockout.rawValue {
                    DispatchQueue.main.async {
                        let vc = self.presentingViewController
                        self.dismiss(animated: true, completion: nil)
                        self.验证手机锁屏密码(vc)
                    }
                    return
                }
            }
            tapPwdBtn()
        }
    }
    
    // MARK: CTAPIManagerParamSource
    func params(forApi manager: CTAPIBaseManager!) -> [AnyHashable : Any]!
    {
        return [kApiParamPayPwd: pwdTF.text!]
    }
    
    // MARK: CTAPIManagerCallBackDelegate
    func managerCallAPIDidSuccess(_ manager: CTAPIBaseManager!) {
        hideLoading()
        _verifyApiManager = nil
        dismiss(animated: true, completion: nil)
        if self.didConfirmBtn != nil {
            self.didConfirmBtn!(self)
        }
    }
    
    func managerCallAPIDidFailed(_ manager: CTAPIBaseManager!) {
        hideLoading()
        alert(manager.errorMessage)
        _verifyApiManager = nil
    }
    
    // MARK: - Event repsond
    /// 点击确定按钮
    @IBAction func tapConfirmBtn()
    {
        if pwdType { // 密码支付
            if pwdTF.text!.isEmpty {
                alert(LocalStr("请输入支付密码"))
                return
            }
            
            showLoading()
            verifyApiManager.loadData()
            
        } else { // 指纹支付
            let vc = presentingViewController
            dismiss(animated: true, completion: nil)
            pwdType = true
            
            let content = LAContext()
            content.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: LocalStr("请验证指纹，完成支付")) { (flag, error) in
                if flag {
                    DispatchQueue.main.async {
                        if self.didConfirmBtn != nil {
                            self.didConfirmBtn!(self)
                        }
                    }
                    
                } else {
                    if let error = error as NSError? {
                        
                        if #available(iOS 9.0, *) {
                            if error.code == LAError.touchIDLockout.rawValue {
                                DispatchQueue.main.async {
                                    self.验证手机锁屏密码(vc)
                                }
                                return
                            }
                        }
                        
                        if error.code == LAError.userFallback.rawValue ||
                            error.code == LAError.authenticationFailed.rawValue
                        {
                            DispatchQueue.main.async {
                                vc?.present(self, animated: true, completion: {
                                    self.pwdTF.becomeFirstResponder()
                                })
                            }
                        }
                        else {
                            DispatchQueue.main.async {
                                if self.didCancelBtn != nil {
                                    self.didCancelBtn!(self)
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    
    /// 点击关闭按钮
    @IBAction func tapCloseBtn() {
        dismiss(animated: true, completion: nil)
        if didCancelBtn != nil {
            didCancelBtn!(self)
        }
    }
    
    /// 点击输入密码按钮
    @IBAction func tapPwdBtn () {
        pwdType = true
        pwdTF.becomeFirstResponder()
    }
    
    // MARK: -
    @available(iOS 9.0, *)
    func 验证手机锁屏密码(_ vcToPresent: UIViewController?) {
        let content = LAContext()
        content.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: LocalStr("请验证手机锁屏密码，解锁指纹"), reply: { (flag, error) in
            if flag {
                DispatchQueue.main.async {
                    self.pwdType = false
                    vcToPresent?.present(self, animated: true, completion: {
                        self.pwdTF.resignFirstResponder()
                    })
                }
            }
            else {
                DispatchQueue.main.async {
                    if self.didCancelBtn != nil {
                        self.didCancelBtn!(self)
                    }
                }
            }
        })
    }
    
    
    // MARK: - Get
    
    var pwdType: Bool = false {
        didSet {
            rhLabel.isHidden = pwdType
            amountLabel.isHidden = pwdType
            titleLabel.text = pwdType ? LocalStr("请输入支付密码") :  LocalStr("指纹支付")
            pwdTF.isHidden = !pwdType
            typeBtn.isHidden = pwdType
        }
    }
    
    @IBOutlet private weak var alertView: UIView!
    
    @IBOutlet private weak var titleLabel: UILabel!
    @IBOutlet private weak var typeBtn: UIButton!
    
    @IBOutlet private weak var rhLabel: UILabel!
    @IBOutlet private weak var amountLabel: UILabel!
    
    @IBOutlet private weak var pwdTF: UITextField!
    
    var money: String!
    
    var didConfirmBtn: ((_ vc: ConfirmPayVC)->Void)?
    var didCancelBtn: ((_ vc: ConfirmPayVC)->Void)?
    
    var _verifyApiManager: VerifyPayPwdApiManager?
    var verifyApiManager: VerifyPayPwdApiManager {
        if _verifyApiManager == nil {
            _verifyApiManager = VerifyPayPwdApiManager()
            _verifyApiManager!.paramSource = self
            _verifyApiManager!.delegate = self
        }
        return _verifyApiManager!
    }
    
}
